In [ ]:
mytuple = ("sausage", "eggs", "bacon")
type(mytuple)
mylist = list(mytuple)
Attempt to append the string "spam"
to mylist and mytuple using append.
In [ ]:
mylist.append("spam")
mytuple.append("spam")
List objects have a sort() function, use that for sorting the list alphabetically (e.g. mylist.sort() ). What is now the first item of the list?
Next, remove the first item from the list, investigate the contents and remove then last item from the list.
In [ ]:
mylist.sort()
print(mylist[0])
del mylist[-1]
print(mylist)
In [ ]:
numbers = list(range(50, 0, -2))
Using slicing syntax, select
In [ ]:
print(numbers[-4])
print(numbers[10:14])
print(numbers[:5])
Read up on the stride syntax . Then using it select
In [ ]:
print(numbers[::3])
print(numbers[1::2])
In [ ]:
coordinates = [[0.1, 4.5], [-1.2, 3], [2.2, -5], [3.4, 1.6]]
Create a dictionary whose keys are the fruits “pineapple”, “strawberry”, and “banana”. As values use numbers representing e.g. prices.
Add “orange” to the dictionary and then remove “banana” from the dictionary. Investigate the contents of dictionary and pay attention to the order of key-value pairs.
In [ ]:
fruits = {'banana' : 5, 'strawberry' : 7, 'pineapple' : 3}
print(fruits)
fruits['orange'] = 4.5
print(fruits)
del fruits['banana']
print(fruits)
In [ ]:
apple = {'color' : 'green', 'weight' : 120}
orange = {'color' : 'orange', 'weight' : 110}
fruits = {'apple' : apple, 'orange' : orange}
print(fruits)
fruits['apple']['color'] = 'red'
print(fruits)
It is often useful idiom to create empty lists or dictionaries and add contents little by little.
Create first an empty dictionary for a mid-term grades of students. Then, add a key-value pairs where the keys are student names and the values are empty lists.
Finally, add values to the lists and investigate the contents of the dictionary.
In [ ]:
grades = {}
grades['Jussi'] = []
grades['Jyry'] = []
print(grades)
grades['Jussi'].append(2)
grades['Jyry'].append(5)
print(grades)
grades['Jussi'].append(3)
grades['Jyry'].append(4)
print(grades)